/*
Source : https://leetcode.com/problems/count-and-say/
Author : nflush@outlook.com
Date   : 2016-08-25
*/

/*
38. Count and Say

    Total Accepted: 93989
    Total Submissions: 306614
    Difficulty: Easy

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

Subscribe to see which companies asked this question
*/
class Solution {
public:
    string countAndSay(int n) {
        vector<int> ret(1, 1);
        if (n <= 1){
            return string("1");
        }
        while (--n){
            ret = getNext(ret);
        }
        return arrayTostr(ret);
    }
private:
    string arrayTostr(vector<int> nums){
        std::stringstream s;
        for (auto i : nums){
            s << i;
        }
        return s.str();
    }
    vector<int>getNext(vector<int> v){
        vector<int> ret;
        int size = v.size();
        int val = v[0];
        int cnt = 1;
        for (int i = 1; i < size; i++){
            if (val == v[i]){
                cnt++;
            } else{
                ret.push_back(cnt);
                ret.push_back(val);
                val = v[i];
                cnt = 1;
            }
        }
        ret.push_back(cnt);
        ret.push_back(val);
        return std::move(ret);
    }

};


